package com.ibitcube.http.api.util;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;


@SuppressWarnings("all")
public class HttpUtil {

	// 接口地址
	private String apiURL;
	private CloseableHttpClient httpClient = null;
	private HttpPost httpPost = null;
	private HttpGet httpGet = null;
	private long startTime = 0L;
	private long endTime = 0L;
	private int status = 0;
	public final static String POST = "POST";
	public final static String GET = "GET";

	private static final String APPLICATION_JSON = "application/json; charset=utf-8";
	private static final String CONTENT_TYPE_TEXT_JSON = "text/json;charset=utf-8";
	

	public HttpUtil() {

	}

	/**
	 * 接口地址
	 * 
	 * @param url
	 */
	public HttpUtil(String url, String method) {

		if (url != null) {
			this.apiURL = url;
		}
		if (apiURL != null) {
			httpClient = HttpClients.createDefault();

			if (POST.equals(method)) {
				httpPost = new HttpPost(this.apiURL);
			} else if (GET.equals(method)) {
				httpGet = new HttpGet(url);
			}

		}
	}

	public static String getSign(Map<String, Object> map, String key) {
		ArrayList<String> list = new ArrayList<String>();
		for (Map.Entry<String, Object> entry : map.entrySet()) {
			if (entry.getValue() != "") {
				list.add(entry.getKey() + "=" + entry.getValue() + "&");
			}
		}
		int size = list.size();
		String[] arrayToSort = list.toArray(new String[size]);
		Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < size; i++) {
			sb.append(arrayToSort[i]);
		}
		String result = sb.toString() + "key=" + key;
		result = MD5.encryption(result).toUpperCase();
		return result;
	}

	/*
	 * post请求，
	 */
	public String post(String parMap) {
		InputStream input = null;// 输入流
		InputStreamReader isr = null;
		BufferedReader buffer = null;
		StringBuffer sb = null;
		String line = null;
		try {
			/* post向服务器请求数据 */
			StringEntity se = new StringEntity(parMap, "utf-8");
			httpPost.addHeader("Content-Type", APPLICATION_JSON);
			//httpPost.setHeader("Accept", CONTENT_TYPE_TEXT_JSON);
			httpPost.setEntity(se);
			startTime = System.currentTimeMillis();
			HttpResponse response = httpClient.execute(httpPost);
			endTime = System.currentTimeMillis();
			int statusCode = response.getStatusLine().getStatusCode();

			System.out.println("响应码:" + statusCode);
			System.out.println("请求耗时:" + (endTime - startTime) + "毫秒");

			// 若状态值为200，则ok
			if (statusCode == HttpStatus.SC_OK) {
				// 从服务器获得输入流
				input = response.getEntity().getContent();
				isr = new InputStreamReader(input);
				buffer = new BufferedReader(isr, 10 * 1024);

				sb = new StringBuffer();
				while ((line = buffer.readLine()) != null) {
					sb.append(line);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				if (buffer != null) {
					buffer.close();
					buffer = null;
				}
				if (isr != null) {
					isr.close();
					isr = null;
				}
				if (input != null) {
					input.close();
					input = null;
				}
			} catch (Exception e) {
			}
		}
		return sb.toString();
	}
	
	public static void main(String[] args) throws Exception {
		
	}

}
